<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form >
        <input type="text" name="name" id="name">
        <input type="text" name="age" id="age">
        <input type="text" name="sex" id="sex">
        <button>提交</button>
    </form>

    <script>
        const form = document.querySelector('form')
        const intNodes = document.querySelectorAll('input')
        form.onsubmit = function () {
            // 收集表单信息
            const bodyname = intNodes[0].value
            const bodyage = intNodes[1].value
            const bodysex = intNodes[2].value
            const xhr = new XMLHttpRequest()
            xhr.open('POST', '/addmsg', true)
            xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")
            xhr.send(JSON.stringify({
                name: bodyname,
                age: bodyage,
                sex: bodysex
            }))
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status <= 299) {
                    const result = JSON.parse(xhr.responseText)
                    console.log(result); 
                }

            }
            return false;
        }




            // const form = document.querySelector('form')
            // const getname = document.querySelector('#name')
            // const getage = document.querySelector('#age')
            // const getsex = document.querySelector('#sex')

            // form.onsubmit = function(){
            //     const userId = getname.value;
            //     const userAge = getage.value;
            //     const userSex = getsex.value;

            //     const xhr = new XMLHttpRequest()
            //     xhr.open('post','/addmsg',true)
            //     // xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8") 
            //     xhr.send(`name=${userId},age=${userAge},sex=${userSex}`)  //设置请求体
            //     xhr.onreadystatechange = function(){
            //         if(xhr.readyState === 4 && xhr.status >=200 && xhr.status <= 299){
            //             const result = JSON.parse(xhr.responseText)
            //             console.log(result);
            //         }
            //     }

            //     return false;  // 阻止浏览器默认功能 防止表单提交刷新  ajax是不刷新请求数据
            //  }


    </script>
</body>

</html>